﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Web.SystemConfig.Services;
using Web.SystemConfig.DataAccess;
using System.Data;
using DreamBuilder.Common;
using DreamBuilder.Core.Message;
using System.Web;
using DreamBuilder.UI.UserControls;
using Microsoft.Web.UI.WebControls;
using System.Web.UI;


namespace Web.SystemConfig.Business
{

    public class BUSAuth_User : BusinessBase, IAuth_User
    {
        DALAuth_User dal;
        DALAuth_UserState dalUserState;
        public BUSAuth_User()
        {
            dal = new DALAuth_User();
            dalUserState = new DALAuth_UserState();
        }

        public int IsParentID()
        {
            int ob = dal.IsParentID();
            return ob;
        }


        public DataTable SelectRolesByUserID(string userID)
        {
            return dal.SelectRolesByUserID(userID);
        }

        public string GetUserNameById(string userId)
        {
            DataTable dt = dal.GetUserInfo(userId);
            if (dt.Rows.Count > 0)
            {
                return dt.Rows[0]["User_Name"].ToString();
            }
            else
            {
                return null;
            }
        }

        public DataTable SelectOrgRolesByUserID(string userID)
        {
            return dal.SelectOrgRolesByUserID(userID);
        }
        //by 刘英男修改
        public ResultInfo SaveData(DataSet dsInfo, DreamBuilder.UI.UserControls.EPGridView gv_Role, string userID)
        {
            //保存前获取该用户原来的orgid
            DataTable dtOldOrg = dal.GetUserOldOrg(userID);
            //先保存
            ResultInfo result = base.Save(dsInfo);
            if (result.bSuccess == false)
            {
                return result;
            }
            try
            {
                string roleID = string.Empty;
                string hasRoleSave = "";
                foreach (System.Web.UI.WebControls.GridViewRow gvr in gv_Role.Rows)
                {
                    if (gvr.RowType == System.Web.UI.WebControls.DataControlRowType.DataRow)
                    {
                        Control c = gvr.Cells[1].Controls[0];
                        if (c is System.Web.UI.WebControls.CheckBoxList)
                        {
                            System.Web.UI.WebControls.CheckBoxList cbl = (System.Web.UI.WebControls.CheckBoxList)c;
                            foreach (System.Web.UI.WebControls.ListItem li in cbl.Items)
                            {
                                //get the saved status
                                hasRoleSave = li.Value.Substring(0, 1);
                                //get the roleID
                                roleID = li.Value.Remove(0, 2);

                                //add the UserRole
                                if (hasRoleSave == "0" && li.Selected)
                                {
                                    dal.InsertUserRole(userID, roleID);
                                }
                                //delete the UserRole
                                else if (hasRoleSave == "1" && (!li.Selected))
                                {
                                    dal.DeleteUserRole(userID, roleID);
                                }
                            }
                        }
                    }
                }

                //#region 再处理org_user表联动的数据

                ////如果没有OrgID
                //if (dsInfo.Tables[0].Rows[0]["P_Auth_User.ORG_ID"] == DBNull.Value || dsInfo.Tables[0].Rows[0]["P_Auth_User.ORG_ID"].ToString().Length == 0)
                //{
                //    //删除在orguser表中原有的该用户的部门，多部门在前台验证，所以运行到此说明该用户只有一个部门
                //    dal.DeleteOrgWithoutOrgID(userID);
                //}
                ////有orgid的情况下
                //else
                //{
                //    string orgID = dsInfo.Tables[0].Rows[0]["P_Auth_User.ORG_ID"].ToString();
                //    string PositionID = dsInfo.Tables[0].Rows[0]["P_Auth_User.Position_ID"].ToString();
                //    string OrderNumID = dsInfo.Tables[0].Rows[0]["P_Auth_User.Order_Num"].ToString();
                //    // 如果原来没有orgid,向orguser表插入新的org记录
                //    if (dtOldOrg.Rows.Count == 0 || dtOldOrg.Rows[0]["ORG_ID"] == DBNull.Value || dtOldOrg.Rows[0]["ORG_ID"].ToString().Length == 0)
                //    {
                //        dal.AddOrg(userID, orgID);
                //    }
                //    //如果原来有orgid
                //    else
                //    {
                //        string oldOrgID = dtOldOrg.Rows[0]["ORG_ID"].ToString();
                //        //如果原来的orgid和新的orgid不同的话
                //        if (orgID != oldOrgID)
                //        {
                //            int intNewOrgIDCount = dal.GetNewOrgIDCount(userID, orgID);
                //            //如果原来有新的orgid的话，删除旧的
                //            if (intNewOrgIDCount > 0)
                //            {
                //                dal.DeleteOrg(userID, oldOrgID);
                //            }
                //            //如果原来没有的话，将orguser表中的原来的org改为新的orgid
                //            else
                //            {
                //                dal.UpdateOrg(userID, orgID, oldOrgID);
                //            }
                //        }
                //        //add by 刘英男 将职务和排序加到 部门成员中
                //        string oldPositionID = dtOldOrg.Rows[0]["Position_ID"].ToString();
                //        string oldOrderNumID = dtOldOrg.Rows[0]["Order_Num"].ToString();
                //        //如果原来的PositionID和新的PositionID不同的话
                //        if (PositionID != oldPositionID)
                //        {

                //            dal.UpdatePosition(userID, PositionID, oldPositionID);

                //        }
                //        if (OrderNumID != oldOrderNumID)
                //        {
                //            dal.UpdateOrderNum(userID, OrderNumID, oldOrderNumID);
                //        }
                //    }
                //}

                //#endregion
            }
            catch (System.Data.SqlClient.SqlException sqlErr)
            {
                result.bSuccess = false;
                result.ErrorID = sqlErr.Number.ToString();
            }
            catch (System.Exception err)
            {
                result.bSuccess = false;
                result.ErrorDesc = err.Message;
            }
            return result;
        }

        public DataTable GetUserInfo(string User_ID)
        {
            return dal.GetUserInfo(User_ID);
        }
        public DataTable CheckOrg(DataTable dataTable)
        {
            string userID = dataTable.Rows[0]["P_Auth_User.User_ID"].ToString();
            return dal.GetCheckOrg(userID);
        }
        #region 生成树

        private DataTable dtOrg;

        public DataTable DtOrg
        {
            get
            {
                dtOrg = dal.GetAllOrgData();
                return dtOrg;
            }
        }

        public void CreateTree(TreeView tree)
        {
            if (DtOrg != null && DtOrg.Rows.Count > 0)
            {
                DataRow[] arrDr = DtOrg.Select("Parent_ID is null ");
                if (arrDr == null || arrDr.Length == 0)
                {
                    return;
                }
                else
                {
                    DataRow rootDr = arrDr[0];
                    TreeNode root = new TreeNode();
                    root.ID = rootDr["ORG_ID"].ToString();
                    root.Text = rootDr["ORG_Name"].ToString() + "(" + rootDr["usercount"].ToString() + ")";
                    string url = "../SystemConfig/Auth_User.aspx?Parent_ID=" + rootDr["ORG_ID"].ToString();
                    root.NavigateUrl = "../SystemLogin/loadingpage.aspx?Menu_URL=" + HttpContext.Current.Server.UrlEncode(url);
                    tree.Nodes.Add(root);
                    AddChildNode(root, rootDr["ORG_ID"].ToString());
                }
            }
        }

        private void AddChildNode(TreeNode root, string parentID)
        {
            if (DtOrg != null && DtOrg.Rows.Count > 0)
            {
                DataRow[] arrDr = DtOrg.Select("Parent_ID='" + parentID + "'", "Order_Num");
                if (arrDr == null || arrDr.Length == 0)
                {
                    return;
                }
                foreach (DataRow dr in arrDr)
                {
                    TreeNode child = new TreeNode();
                    child.ID = dr["ORG_ID"].ToString();
                    child.Text = dr["ORG_Name"].ToString() + "(" + dr["usercount"].ToString() + ")";
                    string url = "../SystemConfig/Auth_User.aspx?Parent_ID=" + dr["ORG_ID"].ToString();
                    child.NavigateUrl = "../SystemLogin/loadingpage.aspx?Menu_URL=" + HttpContext.Current.Server.UrlEncode(url);
                    root.Nodes.Add(child);
                    AddChildNode(child, dr["ORG_ID"].ToString());
                }
            }
        }

        #endregion
        #region 根据所属单位获取单位名称 add by 刘英男
        /// <summary>
        /// 根据所属单位获取单位名称
        /// </summary>
        /// <param name="number">组织单元编号</param>
        /// <returns></returns>
        public string GetOrgNameByNumber(string number)
        {
            if (string.IsNullOrEmpty(number))
                return "#Error:所属单位为空!";

            DataTable orgDT = dal.GetORGInfo(number);

            if (orgDT != null && orgDT.Rows.Count > 0)
            {
                return orgDT.Rows[0]["ORG_Name"].ToString();
            }
            return "#Error:未查询到对应所属单位名称!";
        }
        public ResultInfo DeleteUser(string pkValue)
        {
            ResultInfo result = new ResultInfo();
            result.bSuccess = true;
            try
            {
                dal.DeleteUserRole(pkValue);
                //dal.DeleteUserOrg(pkValue);
                dal.DeleteUser(pkValue);
            }
            catch (Exception e)
            {
                result.bSuccess = false;
                result.ErrorDesc = e.Message;
            }
            return result;
        }
        #endregion
        #region add by  刘英男 上移下移用户
        /// <summary>
        /// 上移用户
        /// </summary>
        /// <param name="pkVale">用户编号</param>
        /// <returns></returns>
        public ResultInfo MoveUpOrder(string pkValue)
        {
            ResultInfo result = new ResultInfo();
            result.bSuccess = true;
            try
            {
                dal.MoveUpUser(pkValue);
            }
            catch (Exception e)
            {
                result.bSuccess = false;
                result.ErrorDesc = e.Message;
            }
            return result;
        }
        /// <summary>
        /// 下移用户
        /// </summary>
        /// <param name="pkVale">用户编号</param>
        /// <returns></returns>
        public ResultInfo MoveDownOrder(String pkValue)
        {

            ResultInfo result = new ResultInfo();
            result.bSuccess = true;
            try
            {
                dal.MoveDownUser(pkValue);
            }
            catch (Exception e)
            {
                result.bSuccess = false;
                result.ErrorDesc = e.Message;
            }
            return result;
        }
        #endregion
        #region add by 刘英男  根据所属单位获取最大的排序字段
        /// <summary>
        /// 根据所属单位获取最大的排序字段
        /// </summary>
        /// <param name="orgID">单位编号</param>
        /// <returns></returns>
        public int MaxOrgNum(string orgID)
        {
            //int userorgnum = dal.GetCountUserNum(orgID);
            //if (userorgnum == 0)
            //{
            //    return userorgnum;
            //}
            //else
            //{
            //    int ob = dal.GetMaxOrgNum(orgID);
            //    return ob;
            //}
            int ob = dal.GetMaxOrgNum(orgID);
            return ob;
        }
        #endregion
        #region add by 刘英男 上移下移用户
        /// <summary>
        /// 交换用户排序
        /// </summary>
        /// <param name="userorder">上一个序号</param>
        /// <param name="useridgrid">下一个序号</param>
        /// <returns></returns>
        public void MoveUserOrder(string userorder, string useridgrid)
        {
            dal.ChangUserOrder(userorder, useridgrid);
        }
        #endregion
        #region add by 刘英男 检查用户登录名是否唯一
        /// <summary>
        ///  检查用户登录名是否唯一
        /// </summary>
        /// <param name="loginid">登录名</param>
        /// <returns>是，否</returns>
        public bool CheckLoginID(string loginid)
        {
            int userloginid = dal.CheckLoginID(loginid);
            if (userloginid == 0)
            {
                return false;
            }
            else
            {
                return true;
            }
        }
        #endregion
        #region add by 刘英男 检查用户主键是否唯一
        /// <summary>
        ///  检查用户主键是否唯一
        /// </summary>
        /// <param name="userCheckID">用户登录id</param>
        /// <returns>是,否</returns>
        public bool CheckUserPrimary(string userCheckID)
        {
            int userloginid = dal.CheckUserPrimary(userCheckID);
            if (userloginid == 0)
            {
                return false;
            }
            else
            {
                return true;
            }
        }
        #endregion
        #region add by liuyingnan  职位的最大的排序字段
        /// <summary>
        /// 职位的最大的排序字段
        /// </summary>
        /// <returns>数值</returns>
        public int MaxPositionNum()
        {
            return dal.GetMaxPositionNum();
        }
        #endregion
        #region add by 刘英男 检查职务排序序号是否唯一
        /// <summary>
        ///  检查职务排序序号是否唯一
        /// </summary>
        /// <param name="userOrder">登录名</param>
        /// <returns>是，否</returns>
        public bool CheckPositionOrder(string userOrder)
        {
            int useruserOrder = dal.CheckPositionOrder(userOrder);
            if (useruserOrder == 0)
            {
                return false;
            }
            else
            {
                return true;
            }
        }
        #endregion
        #region add by lyn 20111027
        public bool CheckPositionName(string positionName)
        {
            DataTable dt = dal.CheckPositionNameInfo(positionName);
            bool result = false;
            if (dt != null && dt.Rows.Count > 0)
            {
                result = true;
            }
            return result;
        }
        #endregion
        #region add by 刘英男 检查用户登录名是否唯一
        /// <summary>
        ///  检查用户OA登录名是否唯一
        /// </summary>
        /// <param name="OAloginid">登录名</param>
        /// <returns>是，否</returns>
        public bool OACheckLoginID(string OAloginid)
        {
            int userloginid = dal.CheckOALoginID(OAloginid);
            if (userloginid == 0)
            {
                return false;
            }
            else
            {
                return true;
            }
        }
        #endregion
        #region add by liuyingnan  最小的排序字段
        /// <summary>
        /// 最小的排序字段
        /// </summary>
        /// <returns>数值</returns>
        public int GetMinOrgNum(string orgID)
        {
            return dal.GetMinOrgNum(orgID);
        }
        #endregion

        #region add by 郭垠  检查用户在线状态
        /// <summary>
        /// 检查用户在线状态
        /// </summary>
        /// <param name="UserId"></param>
        /// <returns></returns>
        public bool CheckLoginStatus(string UserId)
        {
            return dalUserState.CheckLoginStatus(UserId);
        }

        /// <summary>
        /// 检查用户是否存在用户状态表
        /// </summary>
        /// <param name="UserId"></param>
        /// <returns></returns>
        public bool CheckUserStateExsist(string UserId)
        {
            return dalUserState.CheckUserStateExsist(UserId);
        }
        #endregion

        #region add byGuoyin  增加在线用户
        /// <summary>
        /// 增加用户到用户状态表(插入的时候为登陆状态)
        /// </summary>
        /// <param name="UserId">用户ID</param>
        /// <param name="RealID">真实ID</param>
        /// <param name="patform">平台信息</param>
        /// <param name="loginIp">登陆IP</param>
        /// <param name="browers">浏览器信息</param>
        /// <returns></returns>
        public bool AddUserToUserState(string UserId, string RealID, string patform, string loginIp, string browers)
        {
            return dalUserState.AddUserToUserState(UserId, RealID, patform, loginIp, browers);
        }

        /// <summary>
        /// 更改用户在线状态
        /// </summary>
        /// <param name="UserId">用户ID</param>
        /// <param name="RealID">真实ID</param>
        /// <param name="patform">平台信息</param>
        /// <param name="loginIp">登陆IP地址</param>
        /// <param name="browers">浏览器信息</param>
        /// <param name="onlineState">在线状态</param>
        /// <returns></returns>
        public bool UpdateUserState(string UserId, string RealID, string patform, string loginIp, string browers, bool onlineState)
        {
            return dalUserState.UpdateUserState(UserId, RealID, patform, loginIp, browers, onlineState);
        }

        /// <summary>
        /// 查询所有在线用户
        /// </summary>
        /// <returns></returns>
        public DataTable GetOnlineUser()
        {
            return dalUserState.GetOnlineUser();
        }

        /// <summary>
        /// 获取当前在线用户人数
        /// </summary>
        /// <returns></returns>
        public int GetOnlineUserNumber()
        {
            return dalUserState.GetOnlineUserNumber();
        }
        #endregion
        #region add by lyn 批量转移用户 20111128
        /// <summary>
        ///   批量转移用户
        /// </summary>
        /// <param name="userId">用户id</param>
        /// <param name="orgId">单位id</param>
        public void UpdateUserTransferDept(string userId, string orgId)
        {
            dal.UpdateUserTransferDeptInfo(userId, orgId);
        }
        #endregion
        #region add by lyn 更新用户个人信息 20111201
        /// <summary>
        ///   更新用户个人信息
        /// </summary>
        /// <param name="userId">用户id</param>
        /// <param name="userName">用户名</param>
        /// <param name="mobile">电话</param>
        /// <param name="fax">传真</param>
        /// <param name="email">电子邮件</param>
        /// <param name="postCode">邮编</param>
        /// <param name="idNumber">身份证号</param>
        /// <param name="vpnNumber">VPN用户名</param>
        /// <param name="erpNumber">ERP号</param>
        /// <param name="insuranceNumber">保险编号</param>
        public void UpdateUserPersonalInfo(string userId, string userName, string mobile, string officePhone, string fax, string email, string postCode, string idNumber, string vpnNumber, string erpNumber, string insuranceNumber, string address)
        {
            dal.UpdateUserPersonalInfo(userId, userName, mobile, officePhone, fax, email, postCode, idNumber, vpnNumber, erpNumber, insuranceNumber, address);
        }
        #endregion

        #region add by guoyin 查询组织机构下的所有用户
        /// <summary>
        /// 查询组织机构下的用户
        /// </summary>
        /// <param name="OrgID">组织机构ID</param>
        /// <returns></returns>
        public DataTable GetOrgUsers(string OrgID)
        {
            return dal.GetOrgUsers(OrgID);
        }

        public DataTable GetAllUsers()
        {
            return dal.GetAllUsers();
        }
        #endregion
        #region 根据用户id查找所有单位信息 add by lyn 20111223
        /// <summary>
        /// 根据用户id查找所有单位信息
        /// </summary>
        /// <param name="OrgID">组织机构ID</param>
        /// <returns></returns>
        public DataTable CheckOrgInfo(string userID)
        {
            return dal.CheckOrgInfo(userID);
        }
        #endregion
        #region 修改登录人，登录时间，修改人，修改时间 add by lyn 20120108
        /// <summary>
        /// 修改登录人，登录时间，修改人，修改时间
        /// </summary>
        /// <param name="tableName">数据库表名</param>
        /// <param name="User">数数库中用户名</param>
        /// <param name="userName">用户名</param>
        /// <param name="Time">数据库中时间</param>
        /// <param name="currentTime">当前时间</param>
        /// <param name="primarykey">数据库主键</param>
        /// <param name="pkValue">主键</param>
        /// <returns></returns>
        public void ModifyUser(string tableName, string User, string userName, string Time, DateTime currentTime, string primarykey, string pkValue)
        {
            dal.ModifyUserInfo(tableName, User, userName, Time, currentTime, primarykey, pkValue);
        }
        #endregion
        #region 新增数据,更新排序字段 add by lyn 20120112
        /// <summary>
        /// 新增数据,更新排序字段
        /// </summary>
        /// <param name="tableName">数据库表名</param>
        /// <param name="OrderNum">数据库排序字段</param>
        /// <param name="primarykey">数据库主键</param>
        /// <param name="pkValue">记录主键</param>
        /// <returns></returns>
        public void UpdateOrderNum(string tableName, string orderNum, string primarykey, string pkValue)
        {
            dal.UpdateOrderNumInfo(tableName, orderNum, primarykey, pkValue);
        }
        #endregion
        #region 根据著作权id获取附件 add by lyn 20110202
        /// <summary>
        /// 根据著作权id获取附件-下载附件
        /// </summary>
        /// <param name="SFID"></param>
        /// <returns></returns>
        public DataTable GetAccBySFID(string tableName, string SFID)
        {
            return dal.GetAccBySFID(tableName, SFID);
        }
        #endregion
        #region 获取下载附件的信息 add by lyn 20111213
        /// <summary>
        /// 获取下载附件的信息
        /// </summary>
        /// <param name="fileID">附件ID</param>
        /// <param name="TID">收发文ID</param>
        /// <param name="TName">发文OR收文</param>
        /// <returns>附件信息</returns>
        public DataTable GetUploadFileInfo(string fileID)
        {
            return dal.GetUploadFileInfo(fileID);
        }
        #endregion
        #region add by lyn 20120419 给用户增加普通用户的角色
        public void UpdateUserRole()
        {
            dal.UpdateUserRoleInfo();
        }
        #endregion


        public List<Guid> GetUserDtByOrgIDAndRoleID(string orgid, string roleID)
        {
            List<Guid> rtnList = null;
            DataTable oDataTable = this.dal.GetUserDtByOrgIDAndRoleID(orgid, roleID);
            if (oDataTable != null && oDataTable.Rows.Count > 0)
            {
                rtnList = new List<Guid>();
                Guid userID = Guid.Empty;
                foreach (DataRow dr in oDataTable.Rows)
                {
                    userID = new Guid(dr["User_ID"].ToString());
                    if (!rtnList.Contains(userID))
                    {
                        rtnList.Add(userID);
                    }
                }
            }

            return rtnList;
        }


        public List<Guid> GetUserDtByQZHAndToRoleID(Guid userID, string roleID)
        {
            List<Guid> rtnList = null;
            DataTable oDataTable = this.dal.GetUserDtByQZHAndToRoleID(userID, roleID);
            if (oDataTable != null && oDataTable.Rows.Count > 0)
            {
                rtnList = new List<Guid>();
                Guid drUserID = Guid.Empty;
                foreach (DataRow dr in oDataTable.Rows)
                {
                    drUserID = new Guid(dr["User_ID"].ToString());
                    if (!rtnList.Contains(drUserID))
                    {
                        rtnList.Add(drUserID);
                    }
                }
            }
            return rtnList;
        }

        public List<Guid> GetUserListByQZHAndToRoleID(string qzh, string roleID)
        {
            List<Guid> rtnList = null;
            DataTable oDataTable = this.dal.GetUserDtByQZHAndToRoleID(qzh, roleID);
            if (oDataTable != null && oDataTable.Rows.Count > 0)
            {
                rtnList = new List<Guid>();
                foreach (DataRow dr in oDataTable.Rows)
                {
                    var drUserID = new Guid(dr["User_ID"].ToString());
                    if (!rtnList.Contains(drUserID))
                    {
                        rtnList.Add(drUserID);
                    }
                }
            }
            return rtnList;
        }


        public string GetQZHByUserID(string userID)
        {
            return this.dal.GetQZHByUserID(userID);
        }
    }
}
